package com.etong.citymap.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.GnssStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;

import com.etong.citymap.activity.R;
import com.etong.citymap.connect.NetOperation;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.util.MapInfoUtil;
import com.etong.citymap.util.log.LogDetailUtil;
import com.etong.citymap.util.log.LogUtil;
import com.supermap.data.Point2D;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class TrajectorySerivice extends Service {

    private static Timer time;
    private CityApplication cityApplication;
    private Point2D lastPoint;

    static LocationListener locationListener;
    static LocationManager locationManager;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onCreate() {
        super.onCreate();

        cityApplication = (CityApplication)getApplication();

        showNotification();

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                LogDetailUtil.d("LocationListener的onLocationChanged获得到的位置信息！location=" + location);
                if(null != location){
                    CityApplication.setLocation(location);
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                LogDetailUtil.d("LocationListener的onStatusChanged获得到的位置信息！provider=" + provider + ";status=" + status + ";extras=" + extras);
            }

            @Override
            public void onProviderEnabled(String provider) {
                LogDetailUtil.w("LocationListener的onProviderEnabled获得到的位置信息！provider=" + provider);
            }

            @Override
            public void onProviderDisabled(String provider) {
                LogDetailUtil.w("LocationListener的onProviderDisabled获得到的位置信息！provider=" + provider);
            }

        };
        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        refreshGPS();//激活卫星

        String gpsProvider = LocationManager.GPS_PROVIDER;

        locationManager.registerGnssStatusCallback(new GnssStatus.Callback() {
            @Override
            public void onSatelliteStatusChanged(GnssStatus status) {
                super.onSatelliteStatusChanged(status);
                LogDetailUtil.d("locationManager.registerGnssStatusCallback的onSatelliteStatusChanged获得到的卫星情况！getSatelliteCount=" + status.getSatelliteCount());
            }
        });
        locationManager.requestLocationUpdates(gpsProvider, 1000, 1, locationListener);

        if(time==null){
            time = new Timer();
            time.schedule(new TimerTask(){
                public void run() {
                    try {
                        Point2D p1 = MapInfoUtil.get2DLocation4Supermap(cityApplication);
                        cityApplication.setGpsPoint(p1);
                        LogDetailUtil.i("TrajectorySerivice通过手机自带功能获得的定位信息！Point2D=" + p1);
                        if (p1 == null) {
                            refreshGPS();//激活卫星
                        }
                        if(p1 !=null && ! p1.equals(lastPoint)){ //如果重复则不提交
                            NetOperation.getNetGps(cityApplication.getGpsPoint(),true, 1,cityApplication.getUserId(),cityApplication.getUserCode(),cityApplication.getHTTPURL());
                            lastPoint = cityApplication.getGpsPoint();
                        }
                    } catch (Exception e) {
                        LogUtil.e(e);
                    }
                }}, 10000,30000); //延迟10秒之后，每30秒循环添加轨迹
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        LogDetailUtil.e("TrajectorySerivice的onDestroy被调用！！！");
        if(!CityApplication.realLogout){
            // 再次拉起service
            stopForeground(true);
            Intent intent = new Intent();
            intent.setClass(this, TrajectorySerivice.class);
            this.startService(intent);
        }

    }

    public static void realStopService(){
        CityApplication.realLogout = true;
        LogDetailUtil.e("TrajectorySerivice的realStopService被调用！！！");
        if(time!=null) time.cancel();
        if(null != locationManager) {
            locationManager.removeUpdates(locationListener);
        }
    }

    public static void refreshGPS(){
        List<String> providers = locationManager.getProviders(true);
        for (int i = 0; i < providers.size(); i++) {
            LogUtil.i("刷新卫星信息 " + i + " 为：" + providers.get(i));
        }
    }

    private String notificationId = "serviceid";
    private String notificationName = "servicename";
    private void showNotification(){
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //创建NotificationChannel
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        startForeground(1,getNotification());
    }
    private Notification getNotification() {
        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle("数字环卫后台定位功能")//设置通知栏标题
                .setContentText("此状态栏是为了提供后台定位功能！")//设置通知栏内容
                .setTicker("数字环卫提示语" + ":" + "正在后台进行定位") //通知首次出现在通知栏，带上升动画效果的
                .setSmallIcon(R.drawable.icon);//设置通知小ICON
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(notificationId);
        }
        Notification notification = builder.build();
        return notification;
    }
}
